package com.ccg.controller;

import com.ccg.entity.Message;
import com.ccg.entity.User;
import com.ccg.service.UserService;
import com.ccg.utils.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;

@Controller
public class RegisterController {

    @Autowired
    UserService userService;

    //注册用户
    @RequestMapping("/addUser")
    @ResponseBody
    public Message addUser(@RequestParam String emailCode,@RequestBody User user, HttpSession session){
        System.out.println(emailCode);
        if(emailCode.equals(session.getAttribute("emailCode"))) {
            session.removeAttribute("emailCode");
            return userService.addUser(user);
        }
        else return new Message(1,"注册账户失败","邮箱验证码错误");
    }


    //获取邮箱验证码
    @RequestMapping("/getEmailCode")
    @ResponseBody
    public Message getEmailCode(@RequestParam String toEmail, HttpSession session) throws MessagingException {
        if(toEmail==null)toEmail="";
        //邮箱地址是否合法
        if(Email.isEmailAddress(toEmail)) {
            //判断改邮箱地址是否被注册
            if (userService.findUserByEmail(toEmail) == null) {
                session.setAttribute("emailCode", Email.getEmailCode());
                Email.sendEmil(toEmail, (String) session.getAttribute("emailCode"));
                return new Message(0, "验证码发送成功", "注意查看");
            }//end 是否被注册
            return new Message(1, "验证码发送失败", "该邮箱地址已被注册");
        }//end
        return new Message(1, "验证码发送失败", "该邮箱地址无效");
    }
}
